package com.sofwin.controller;

import com.sofwin.entity.AjaxResult;
import com.sofwin.pojo.SysResource;
import com.sofwin.service.ResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @packageName: com.sofwin.controller
 * @author: andyliu
 * @date: 2022/5/4 16:06
 * @email 115176513@qq.com
 * @description: TODO
 */
@Api(tags = "资源管理")
@Controller
@RequestMapping("resource")
@Slf4j
public class ResourceController {
    @Autowired
    private ResourceService resourceService;

    @GetMapping
    @ApiIgnore
    public String toData(){
        return "resource/data";
    }
    @GetMapping("toEdit")
    @ApiIgnore
    public String toEdit(Integer id, ModelMap map){
        List<SysResource> resources = resourceService.queryResources(null);
        map.put("resources",resources);
        if(id!=null){
            SysResource resource = resourceService.queryById(id);
            map.put("resource",resource);
        }
        return "resource/edit";
    }
    @GetMapping("/tree")
    @ApiIgnore
    public String tree(){
        return "resource/tree";
    }
    @PostMapping("data")
    @ApiOperation("查询资源列表")
    @ResponseBody
    public AjaxResult data(SysResource resource){
        List<SysResource> resources = resourceService.queryResources(resource);
        return AjaxResult.success(resources);
    }

    @PostMapping("dataCheck")
    @ApiIgnore("根据角色id查询所有资源并显示是否选中")
    @ResponseBody
    public AjaxResult dataCheck(Integer roleId){
        List<SysResource> resources = resourceService.queryResourceByRoleId(roleId);
        return AjaxResult.success(resources);
    }

    @PostMapping("save")
    @ApiOperation("保存资源信息")
    @ResponseBody
    public AjaxResult save(SysResource resource){
        boolean status = resourceService.saveOrUpdateResource(resource);
        if(status){
            return AjaxResult.success(status);
        }
        return AjaxResult.error(status);
    }
    @DeleteMapping("delete/{id}")
    @ResponseBody
    @ApiOperation("根据id删除资源信息")
    public AjaxResult delete(@PathVariable Integer id){
        boolean status = resourceService.removeById(id);
        if(status){
            return AjaxResult.success(status);
        }
        return AjaxResult.error(status);
    }

    @DeleteMapping("deletes")
    @ResponseBody
    @ApiOperation("批量删除资源信息")
    public AjaxResult deletes(@RequestParam(name="ids[]") Integer[] ids){
        boolean status = resourceService.removeByIds(ids);
        if(status){
            return AjaxResult.success(status);
        }
        return AjaxResult.error(status);
    }
}
